package com.haruhinav.Utils;

import com.haruhinav.entity.EmailDetails;
import com.haruhinav.entity.YiBanRemindPunch;
import com.haruhinav.mapper.YiBanRemindPunchMapper;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class MailUtils {

//    发件人
    private final String SENDER = "1527188922@qq.com";
    @Autowired
    JavaMailSenderImpl javaMailSender;

    @Autowired
    YiBanRemindPunchMapper remindPunchMapper;

    @Async //标注为异步类
    @Scheduled(cron = "0 30 10 * * ?") //每天10点30分
    public void autoRemindToPunchIn(){
        EmailDetails emailDetails = remindPunchMapper.getEmailDetails();
        YiBanRemindPunch yiBanRemindPunch = new YiBanRemindPunch();
        yiBanRemindPunch.setIsOpen(1);//查询条件 查询出打开提示的所有用户
        List<YiBanRemindPunch> list = remindPunchMapper.queryYiBanRemindPunch(yiBanRemindPunch);

//        由于setTo() 需要一个string数组而不是集合
//        将集合里的邮箱填入数组
        String[] emails = new String[list.size()];
        for (int i = 0,len = emails.length;i < len;i++){
            emails[i] = list.get(i).getEmail();
        }

        SimpleMailMessage mailMessage = new SimpleMailMessage();
        mailMessage.setSubject(emailDetails.getSubject());
        mailMessage.setText(emailDetails.getText());
        mailMessage.setTo(emails);
        mailMessage.setFrom(SENDER);
        javaMailSender.send(mailMessage);

        /**
         * 添加字段，剩余提醒天数，总提醒天数
         * 查询出isopen = 1 and 剩余天数>0 的用户进行发送
         * 在发送邮件后，剩余天数-1，总提醒天数+1
         *
         * 多修改一个字段 剩余天数可修改
         * */

    }

//    自定义发送 简单邮件
    @Async //标注为异步类
    public void sendCustomSimpleMail(String subject,String text,String... to){
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        mailMessage.setSubject(subject);
        mailMessage.setText(text);
        mailMessage.setTo(to);
        mailMessage.setFrom(SENDER);
        javaMailSender.send(mailMessage);
    }

//    由于外部设置附件功能目前不知道如何实现，所有暂时不做自定义发送复杂邮件
}
